#!/bin/sh
# Solaris style ptree
# by Jagadish Manchala

[ -x /usr/bin/ptree ] && exec /usr/bin/ptree "$@"

# Print process tree
# $1 = PID : extract tree for this process
# $1 = user : filter for this (existing) user
# $1 = user $2 = PID : do both

PATH=/bin:/usr/bin:/usr/sbin:/sbin
export PATH

psopt="-e"
case $1 in
    [a-z]*) psopt="-u $1";shift;;
esac

[ -z "$1" ] &&
exec ps $psopt -Ho pid=,args=

#some effort to add less to the ps list
tmp=/tmp/ptree.$$
trap 'rm $tmp' 0 HUP INT TERM
ps $psopt -Ho pid=,args= >$tmp
<$tmp awk '
{ ci=index(substr($0,7),$2); o[ci]=$0 }
ci>s[a] { s[++a]=ci }
$1==pid {
for(i=1;i<=a;i++) {
    si=s[i]; if(si<=ci) print o[si]
}
walkdown=ci
next
}
ci<walkdown { exit }
walkdown!=0 { print }
' pid="$1"
